package com.mlink.ai.chat.ui.fragment

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.FileProvider
import androidx.fragment.app.DialogFragment
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.DialogBottomChatSelectPhotoBinding
import com.mlink.ai.chat.utils.BitmapUtils
import com.mlink.ai.chat.utils.FileUtils
import com.mlink.ai.chat.utils.dp2px
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

class SelectPhotoBottomDialogFragment : BottomSheetDialogFragment() {

    private val binding: DialogBottomChatSelectPhotoBinding by lazy {
        DialogBottomChatSelectPhotoBinding.inflate(layoutInflater)
    }
    var listener: OnPhotoSelectListener? = null
    var currentPath: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        initView()
        return binding.root
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            setOnKeyListener { _, keyCode, keyEvent ->
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == KeyEvent.ACTION_UP) {
                    dismiss()
                    true
                } else {
                    false
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.run {

            val parent = view?.parent as? ViewGroup
            parent?.setBackgroundResource(R.color.transparent)

            view?.layoutParams?.height = 220.dp2px()
        }
    }

    private fun initView() {
        binding.rlCamera.setOnClickListener {
            val dir = File(FileUtils.getCacheDir(requireContext()), "pic")
            val file = File(dir, "selectTemp.jpeg")
            if (!dir.exists()) {
                dir.mkdirs()
            }
            if (!file.exists() && dir.isFile) {
                file.createNewFile()
            }
            val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(
                    requireContext(),
                    "${requireActivity().packageName}.fileprovider",
                    file
                )
            } else {
                Uri.fromFile(file)
            }
            currentPath = file.absolutePath
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
            try {
                startActivityForResult(intent, CODE_REQUEST_CAMERA)
            } catch (_: Exception) {
                // do nothing now
            }
        }

        binding.rlPhoto.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            try {
                startActivityForResult(intent, CODE_REQUEST_PHOTOS)
            } catch (_: Exception) {
                // do nothing now
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            CODE_REQUEST_CAMERA -> {
                if (BitmapUtils.getBitmapDegree(currentPath) != 0) {
                    BitmapUtils.rotatePicture(File(currentPath))
                }
                listener?.onPhotoSelect(currentPath, FROM_CAMERA)
            }

            CODE_REQUEST_PHOTOS -> {

                data?.data?.let { uri ->
                    val input = context?.contentResolver?.openInputStream(uri)
                    input ?: return
                    val dir = File(FileUtils.getCacheDir(requireContext()), "pic")
                    val file = File(dir, "selectTemp.jpeg")
                    if (!dir.exists()) {
                        dir.mkdirs()
                    }
                    if (!file.exists() && dir.isFile) {
                        file.createNewFile()
                    }
                    try {
                        FileOutputStream(file).use { outputStream ->
                            val buffer = ByteArray(1024)
                            var length: Int
                            while (input.read(buffer).also { length = it } > 0) {
                                outputStream.write(buffer, 0, length)
                            }
                        }
                    } finally {
                        input.close()
                    }
                    listener?.onPhotoSelect(file.absolutePath, FROM_GALLERY)
                }
            }
        }

    }

    interface OnPhotoSelectListener {
        fun onPhotoSelect(uri: String, from: String)
    }

    companion object {
        private const val CODE_REQUEST_CAMERA = 101
        private const val CODE_REQUEST_PHOTOS = 102

        const val KEY_URI = "key_uri"
        const val KEY_PHOTO_FROM = "key_photo_from"
        const val FROM_CAMERA = "from_camera"
        const val FROM_GALLERY = "from_gallery"
    }

}